<?php

namespace app\admin\controller\sms;

use app\common\controller\Backend;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use TencentCloud\Sms\V20190711\SmsClient;
use think\Config;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Sms extends Backend
{

    /**
     * Sms模型对象
     * @var \app\admin\model\sms\Sms
     */
    protected $model = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sms\Sms;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function public_send_sms()
    {
        $id 		= input('id','0','intval');
        $send_type	= input('send_type',1,'intval'); //1客户;2查勘员
        $is_send	= input('is_send',0,'intval');//1发送短信;0生成短信模板
        $chakan_ren	= input('chakan_ren','','trim');//查勘人
        $chakan_ren = Db::name('admin')->where('id',$chakan_ren)->value('username');
        $chakan_mobile	= input('chakan_mobile','','trim');//查勘人手机号
        $where = ['id'=>$id];
        $field = "baoan_id,chakan_ren,mobile,learned_name,baoan_ren,baoan_phone,car_ren,car_num,chuxian_time,address,shigu_condition,tong_number";
        $info = db('baoan')->where($where)->field($field)->find();
        if(empty($info)) $this->error("记录不存在");
        $config = Config::get('site');//短信配置
        $param = [];
        if($send_type == 1){  //客户
            $mobile = $info['baoan_phone'];
            $name 	= $info['baoan_ren'];
            $tpl_id  = $config['sms_customer_tpl_id'];  //模板id
            $tpl 	 = $config['sms_customer_tpl'];		//短信模板
            $param[] = $info['baoan_id']; 			//报案编号
            /*
            $param[] = $info['chakan_ren']; 		//查勘员
            $param[] = $info['mobile'];				 //查勘员-电话
            */
            $param[] = $chakan_ren;					 //查勘员-电话
            $param[] = $chakan_mobile;				 //查勘员-电话
        }else{	//查勘员
            /* $mobile = $info['mobile']; */
            $mobile  = $chakan_mobile;
            $name 	 = $chakan_ren;
            $tpl_id  = $config['sms_ck_tpl_id']; 		//模板id
            $tpl 	 = $config['sms_ck_tpl'];			//短信模板
            $param[] = $info['baoan_id']; 			//报案编号
            $param[] = $info['learned_name']; 		//被服务人
            $param[] = $info['baoan_ren']; 			//报案人
            $param[] = $info['baoan_phone']; 		//报案人手机号
            $param[] = $info['car_ren']; 			//驾驶员
            $param[] = $info['car_num']; 			//牌照
            $param[] = !empty($info['chuxian_time'])?date('Y-m-d H:i',$info['chuxian_time']):''; //出险时间
            $param[] = $info['address']; 			//出险地
            $param[] = $info['shigu_condition']; 	//责任类型
            $param[] = $this->getCantype($info['tong_number']);//参统类别
        }
        $tpl = vsprintf($tpl,$param);
        // if(!$is_send) $this->success($tpl);
        $admin = $this->auth->getUserInfo();
        if (!$is_send) {
            // 记录到调度日志
            $log['bid'] = $id;
            $log['create_time'] = time();
            $log['userid'] = $admin['id'];
            $log['user_name'] = $admin['username'];
            $log['chakan_user_id'] = 0;
            $log['task'] = "";
            $log['task_num'] = "";
            $log['remark'] = $tpl;
            db('diaodu_log')->insert($log);
            // 结束
            $this->success($tpl);
        }
        if(empty($mobile)) $this->error("电话为空，不能发送短息");
        $res = $this->do_send($mobile,$tpl_id,$param);
        $sms = ['create_time'=>time(),'content'=>$tpl,'mobile'=>$mobile,'name'=>$name,'status'=>1];
        $send_status = "发送失败";
        if(isset($res['SendStatusSet'])) {
            $send = current($res['SendStatusSet']);
            if(!isset($send['Code']) || strtolower($send['Code']) != "ok") { //发送失败
                $sms['status'] = 0;
                $sms['reason'] = $send_status = $send['Message'];
            }
        }
        $rs = db('sms_log')->insert($sms);
        if(empty($rs)) $this->error($send_status);
        $this->success("发送成功");
    }


    /*
     ** 短信发送日志
     */
    public function sms_log()
    {
        $name		= input('name','','trim');
        $mobile		= input('mobile','','trim');
        $start_time	= input('start_time','','trim');
        $end_time	= input('end_time','','trim');
        $where = [];
        if(strlen($name) > 0) $where['name'] = ["like","%{$name}%"];
        if(strlen($mobile) > 0) $where['mobile'] = ["like","%{$mobile}%"];
        if(strlen($start_time) > 0) $where['create_time'] = ["egt",strtotime($start_time)];
        if(strlen($end_time) > 0) $where['create_time'] = ["elt",strtotime($end_time ." 23:59:59")];
        $list = db('sms_log')->where($where)->order('id desc')->paginate(10,false,['query'=>$where]);
        $this->assign('list',$list);
        $this->assign('sms_status',config('sms_status'));
        return $this->fetch('conf/sms_log');
    }
    /*
    ** 获取参统类型
    */
    public function getCantype($tong_number)
    {
        $name = "";
        if(empty($tong_number)) return $name;
        $info = db('list_one')->where('tong_number',$tong_number)
            ->field('id,ids,yw_come,yw_class,yw_peo,yw_peo_phone,yw_belonger,yw_handle,yw_join_time,yw_enter_peo,yw_hetongpeo,yw_hetong_time,yw_finance_peo,yw_shenhe_time,tong_storage,tong_number,tong_document,give_company,give_starttime,give_endtime,car_num,car_is_new,car_num_kind,haocolor,car_province,car_check,car_check_res,car_owner,car_card_kind,car_card,car_relation,car_address,car_vin,car_engine,car_factory_num,car_register,car_age,car_issue_time,car_is_transfer,car_buy,car_reall,car_use_nature,car_leixing,car_kind,car_carry_peo,car_carry_quality,car_curb_weight,car_displacement,car_power,car_lastyear,car_rank,plan_strattime,plan_endtime,main_name,main_money,main_standard,main_discount,main_submit,main_franchise,main_disan,main_santong,main_biao,main_zhe,main_yingjiao,main_ji,dao_name,dao_tong,dao_biao,dao_zhe,dao_ying,dao_ji,siji,siji_tong,siji_biao,siji_zhe,siji_ying,siji_ji,chengke,ck_money,chengke_zuo,ck_tong,ck_biao,ck_zhe,ck_ying,ck_ji,buji,bu_tong,bu_biao,bu_zhe,bu_ying,bu_buji,ziran,zi_tong,zi_biao,zi_zhe,zi_ying,zi_buji,fdjsunshi,fdj_tong,fdj_biao,fdj_zhe,fdj_ying,fdj_buji,zdxiuli,zd_tong,zd_biao,zd_zhe,zd_ying,zd_buji,huowu,hw_tong,hw_biao,hw_zhe,hw_ying,hw_buji,boli,bl_tong,bl_biao,bl_zhe,bl_ying,bl_buji,main_sum,main_sumdiscount,main_free,main_netrate,main_netcost,ginseng_name,ginseng_kind,ginseng_card,ginseng_phone,ginseng_email,ginseng_address,learned_name,learned_kind,learned_num,learned_phone,learned_email,learned_address,resolvent,special,invoice_kind,invoice_name,invoice_num,invoice_bank,bank_address,invoice_phone,beizhu,zhanghao,file,file_name,shuoming,shenhe_time,shenhe_peo,shenhe_yijian,status,statuss,pigai_type,pigai_numz,pigai_nump,pigai_piwen,pigai_ctime,pigai_pddzh,main_tongchoufee_heji,main_xiaoguan_bili,main_xiaoguan,main_yunying_bili,main_yunying,main_tongchoujingfee_heji,dong_fee,ncd,give_number,kehu_sumdiscount,chexing,chexing_ci,feiyong,jiafei,jiaofei,jiaofei_price,jiaofei_time,jiaofei_type,trade_no,out_trade_no,type,lururen,lururen_id,feiyong_type,feiyong_qita,jiafei_type,shui_lv1,shui_lv,ziran_c,fd_c,zd_c,huowu_c,boli_c,urls1,urls2,tcxm,status_type,qianzi_status,pdf,chezhu,tk_type,bjt,gs_type,zq_id')
            ->find();
        if(empty($info)) return $name;
        $name = [];
        $config = Config::get('site');
        $task_tong = $config['sms_task_tong']; //参统类型
        foreach($task_tong as $key=>$val) {
            if(!isset($info[$key]) || empty($info[$key])) continue;
            $name[] = $val;
        }
        $name = implode('、',$name);
        return $name;
    }
    /*
    ** 发送短信
    */
    public function do_send($mobile,$tpl_id,$param)
    {
        $config = Config::get('site');//短信配置
        $cred = new Credential($config['sms_secret_id'], $config['sms_secret_key']);
        $httpProfile = new HttpProfile();
        $httpProfile->setReqMethod("GET");  // POST 请求（默认为 POST 请求）
        $httpProfile->setReqTimeout(30);    // 请求超时时间，单位为秒（默认60秒）
        $httpProfile->setEndpoint("sms.tencentcloudapi.com");  // 指定接入地域域名（默认就近接入）
        $clientProfile = new ClientProfile();
        $clientProfile->setSignMethod("TC3-HMAC-SHA256");  // 指定签名算法（默认为 HmacSHA256）
        $clientProfile->setHttpProfile($httpProfile);

        $client = new SmsClient($cred, "ap-shanghai", $clientProfile);
        $req = new SendSmsRequest();
        $req->SmsSdkAppid = $config['sms_app_id'];
        $req->Sign = $config['sms_sign'];
        $req->ExtendCode = "0";
        $req->PhoneNumberSet = array("+86".$mobile);
        $req->SenderId = "";
        $req->SessionContext = time();
        $req->TemplateID = $tpl_id;
        $req->TemplateParamSet = $param;
        $resp = $client->SendSms($req);
        $result = json_decode($resp->toJsonString(),true);
        return $result;
    }


}
